package com.gzu;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")
public class LoginFilter implements Filter {
    //排除列表
    private final List<String> excludePaths = Arrays.asList("/login", "/register", "/public");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取请求URL
        String reqURI = req.getRequestURI();

        // 检查请求URI是否在排除列表中
        if (isExcluded(reqURI)) {
            //如存在 则放行
            filterChain.doFilter(req, resp);
        } else {
            //不存在 则检查是否登录
            HttpSession session = req.getSession();
            if (session != null) {
                User user = (User) session.getAttribute("user");

                if (user!=null && !"".equals(user.getUserName()) && !"".equals(user.getPassword())) {
                    //用户已经登录 则放行
                    filterChain.doFilter(req, resp);
                } else {
                    //用户未登录 跳转到登录页面
                    resp.sendRedirect(req.getContextPath() + "/login.jsp");
                }
            }
        }
    }

    @Override
    public void destroy() {
    }

    //判断url是否在排除列表里
    private boolean isExcluded(String reqURI) {
        //如存在返回true
        for (String path : excludePaths) {
            if (reqURI.contains(path)) {
                return true;
            }
        }
        return false;
    }
}
